package cn.bugstack.domain.activity.service.trial.node;

import cn.bugstack.domain.activity.model.entity.MarketProductEntity;
import cn.bugstack.domain.activity.model.entity.TrialBalanceEntity;
import cn.bugstack.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.bugstack.domain.activity.service.trial.AbstractGroupByMarketSupport;
import cn.bugstack.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.bugstack.types.design.framework.tree.StrategyHandler;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: 小新
 * @Date: 2025/7/20 14:46
 * @Description:
 * @Version: v1.0
 */


@Slf4j
@Service
public class TagNode extends AbstractGroupByMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {

   @Resource
   private EndNode endNode;

    @Override
    protected TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("拼团商品标签过滤服务-TagNode userId:{} requestParameter:{}", requestParameter.getUserId(), JSON.toJSONString(requestParameter));
        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        String tagId = groupBuyActivityDiscountVO.getTagId();
        String tagScope = groupBuyActivityDiscountVO.getTagScope();

        boolean enable = groupBuyActivityDiscountVO.isEnable();
        boolean visible = groupBuyActivityDiscountVO.isVisible();

        // 如果tagId为空，即活动没有配置标签，所有人可见可参与，不需要过滤
        if(StringUtils.isBlank(tagId)){
            dynamicContext.setVisible(visible);
            dynamicContext.setEnable(enable);
            return router(requestParameter, dynamicContext);
        }

        // tagId非空，则进行标签过滤，判断用户在标签范围内,只要在标签内，则可见可参与
        boolean isWithin=repository.isTagCrowdRange(tagId,requestParameter.getUserId());
        dynamicContext.setVisible(visible||isWithin);
        dynamicContext.setEnable(enable||isWithin);
        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return endNode;
    }
}
